import axios from "axios";
import router from "../router/index";
import {Message} from 'element-ui'

//1.创建实例
const instance = axios.create({
    baseURL: 'http://localhost:8081/',
    timeout: 5000,
    headers: {
        'Content-Type': "application/json; charset=utf8"
    }
})

instance.interceptors.request.use(config=>{
    let token= sessionStorage.getItem("token");
    if(token!=null){
        config.headers['authorization'] =token;
        console.log("token:"+token)
    }
    return config;
})

//响应拦截器
instance.interceptors.response.use(response=>{
    //业务逻辑错误
    console.log("response ->" + response)
    let res = response.data

    if (res.code === 200) {
        if (res.msg)
            Message.success(res.msg)
        return response;
    } else {
        Message.error(!res.msg ? '系统异常' : res.msg)
        return Promise.reject(response.data.msg)
    }
},error => {
    //统一处理错误信息
    if (error.response.code==504||error.response.code==404){
        Message.error({message:'服务器挂掉了o(╯□╰)o'})
    }else if (error.response.code==403){
        Message.error({message:'权限不足,请联系管理员'})
    }else if (error.response.code==401){
        Message.error({message:'尚未登录,请登录'})
        router.replace('/login');
    }else {
        if (error.response.data.msg){
            Message.error({message:error.response.data.msg})
        }else {
            Message.error({message:'未知错误!'})
        }
    }
    return;
})

export default instance
